<template>
  <div class="container">
    <van-nav-bar title="转维修" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <van-button class="saveBtn" type="primary" native-type="submit" @click="handleSubmit()">提交</van-button>
    <div class="publicBox formDivBox">
      <van-form ref="form">
        <van-field v-model="ruleForm.applyNo" :disabled="haveCodeRule" name="applyNo" label="申请单号" :rules="haveCodeRule === false ? [{ required: true, message: '请输入申请单号', trigger: 'blur' }] : []" />

        <van-field label="设备编码" :value="ruleForm.equipCode" readonly size="mini" />

        <van-field label="设备名称" :value="ruleForm.equipName" readonly size="mini" />

        <van-field label="所属部门" :value="ruleForm.factoryName" readonly size="mini" />

        <van-field v-model="ruleForm.faultClassifyName" readonly clickable placeholder="请选择" name="faultClassifyName" label="故障分类" :rules="[{ required: true, message: '请选择故障分类', trigger: 'blur' }]" @click="showClassfy = true" />

        <van-field v-model="ruleForm.faultTime" label="故障发生时间" name="faultTime" :rules="[{ required: true, message: '请选择故障发生时间', trigger: 'blur' }]" size="mini" readonly @click="showTime = true" />

        <van-field v-model="ruleForm.emergency" placeholder="请选择" name="emergency" label="紧急度" :rules="[{ required: true, message: '紧急度', trigger: 'blur' }]" size="mini" readonly @click="showEmergency = true" />

        <van-field v-model="ruleForm.faultRemark" :placeholder="ruleForm.faultClassifyName === '' ? '请选择故障分类获取故障描述' :'请输入故障描述'" label="故障描述" :disabled="!ruleForm.faultClassifyName" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />

        <van-field v-model="ruleForm.applyName" name="applyName" placeholder="请选择" label="申请人" :rules="[{ required: true, message: '请选择申请人', trigger: 'blur' }]" size="mini" readonly @click="showUser = true" />

        <van-field v-model="ruleForm.groupName" readonly clickable placeholder="请选择" name="groupName" label="维修班组" :rules="[{ required: true, message: '请选择维修班组', trigger: 'blur' }]" @click="showGroup = true" />

        <van-field v-model="ruleForm.repairUserName" readonly clickable placeholder="请选择" name="repairUserName" label="维修人员" :rules="[{ required: true, message: '请选择维修人员', trigger: 'blur' }]" @click="showUserList = true" />

        <p class="pStyle">自定义字段</p>
        <div class="extensionDiv">
          <van-field v-for="(item, index) in extension" :key="index" v-model="item.value" placeholder="请输入" :name="item.value" :label="item.fieldName" />
        </div>
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 人员选择 -->
    <van-popup v-model="showUser" position="bottom">
      <van-picker title="人员选择" show-toolbar :columns="userList" @confirm="onConfirm" @cancel="showUser = false" />
    </van-popup>
    <!-- 故障分类 -->
    <van-popup v-model="showClassfy" position="bottom">
      <van-picker title="故障分类" show-toolbar :columns="faultClassData" @confirm="onClassfy" @cancel="showClassfy = false" />
    </van-popup>
    <!-- 紧急度 -->
    <van-popup v-model="showEmergency" position="bottom">
      <van-picker title="紧急度" show-toolbar :columns="emergencyList" @confirm="onEmergency" @cancel="showEmergency = false" />
    </van-popup>
    <!-- 维修班组 -->
    <van-popup v-model="showGroup" position="bottom">
      <van-picker title="维修班组" show-toolbar :columns="getGroupListNames" @confirm="onGroupChoice" @cancel="showGroup = false" />
    </van-popup>
    <!-- 维修人 -->
    <van-popup v-model="showUserList" position="bottom">
      <van-picker title="维修人" show-toolbar :columns="userInfoNames" @confirm="onUserChoice" @cancel="showUserList = false" />
    </van-popup>

  </div>
</template>
<script>
import { myFunction } from '@/utils/function'
export default {
  name: 'RepairRequest',
  data () {
    return {
      haveCodeRule: false,
      currentDate: new Date(),
      userList: [],
      emergencyList: ['高', '中', '低'],
      ruleForm: {
        id: '',
        extensionInfo: {},
        emergency: '低',
        factoryName: '',
        equipId: '',
        equipName: '',
        applyNo: '',
        faultClassifyName: '',
        faultClassifyId: '',
        faultRemark: '',
        applyName: JSON.parse(localStorage.getItem('padUserInfo')).data
          .userName, // 申请人
        faultTime: myFunction(new Date()), // 检验时间
        applyBy: JSON.parse(localStorage.getItem('padUserInfo')).data.userId // 本次检验
      },
      show: false,
      code: localStorage.getItem('code'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showUser: false,
      showClassfy: false,
      faultClassData: [],
      faultClassDatas: [],
      showEmergency: false,
      extension: [],
      tableName: 't_equip_repair_order',

	  showGroup: false,
	  showUserList: false,
	  getGroupList: [],
	  getGroupListNames: [],
	  userInfoList: [],
	  userLists: [],
	  userInfo: [],
	  userInfoNames: [],
	  repairUserList: []
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler (row) {}
    }
  },
  created () {
    // this.search.proBatchNo = this.$route.query.code
  },
  mounted () {
    this.getData()
  },
  methods: {
    async getData (row) {
      // const toast = this.$toast.loading({
      //   duration: 0, // 持续展示 toast
      //   message: '数据加载中...',
      //   forbidClick: true,
      //   loadingType: 'spinner'
      // })
      this.detailsObj = this.$store.state.data
      /* 获取人员 */
      await this.getUser()
      await this.getfaultClass()
      await this.getRuleIsOpen()
	  await this.getGroupInfo()
      /* num 1是点检转维修 2是保养转维修 */
      const { nums, equipName, factoryName, factoryId, id, equipCode, equipId } =
        this.detailsObj
      this.ruleForm = {
        ...this.ruleForm,
        equipName: equipName,
        factoryName: factoryName,
        factoryId: factoryId,
        equipId: nums === 1 ? id : equipId,
        equipCode
      }
      const res = await this.$axios.get(
        `/dobo-platform/general/field/extension/${this.tableName}`
      )
      if (res && res.data.code === 200) {
        this.extension = res.data.data
      }
    },
    /* 维修单号是否自动生成 */
    async getRuleIsOpen () {
      this.loading = true
      const res = await this.$axios.get('/dobo-equip/repair/order/ruleIsOpen')
      if (res.data.code === 200 && res.data.data === true) {
        this.haveCodeRule = true
        setTimeout(() => {
          this.loading = false
        }, 300)
      } else {
        this.haveCodeRule = false
        setTimeout(() => {
          this.loading = false
        }, 300)
      }
    },

    /* 获取所有班组 */
    async getGroupInfo () {
	  const res = await this.$axios.get(`/dobo-equip/repair/order/getGroup`)
	  if (res && res.data.code === 200) {
	    this.getGroupList = res.data.data
        res.data.data.forEach((item) => {
		  this.getGroupListNames.push(item.groupName)
        })
	  }
    },

    /* 班组点击事件 */
    groupChange ($event) {
	  this.userInfo = []
	  this.repairUserList = []
	  this.getGroupList.forEach(item => {
	    if (item.groupName === $event) {
	      this.userInfo = item.groupUsers
		  item.groupUsers.forEach((item) => {
		    this.userInfoNames.push(item.userName)
		  })
	    }
	  })
    },

    /** 获取故障分类数据*/
    async getfaultClass () {
      const res = await this.$axios.get(
        '/dobo-equip/equip/fault/classify/getList'
      )
      if (res?.data.code === 200) {
        this.faultClassDatas = res.data.data
        res.data.data.forEach((item) => {
          this.faultClassData.push(item.classifyName)
        })
      }
    },
    /* 获取所有人员 */
    async getUser () {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res.data.code === 200) {
        this.userLists = res.data.data
        res.data.data.forEach((item) => {
          this.userList.push(item.name)
        })
      }
    },
    /* 故障分类选择 */
    onClassfy (e) {
      let id = ''
      let remark = ''
      this.faultClassDatas.forEach((item) => {
        if (item.classifyName === e) {
          id = item.id
          remark = item.remark
        }
      })
      this.ruleForm.faultClassifyId = id
      this.ruleForm.faultRemark = remark
      this.ruleForm.faultClassifyName = e
      this.showClassfy = false
    },
    /* 紧急度选择 */
    onEmergency (e) {
      this.ruleForm.emergency = e
      this.showEmergency = false
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      this.ruleForm.faultTime = myFunction(value)
      this.showTime = false
    },
    /* 人员选择 */
    onConfirm (e) {
      let id = ''
      this.userLists.forEach((item) => {
        if (item.name === e) id = item.id
      })
      this.ruleForm.applyBy = id
      this.ruleForm.applyName = e
      this.showUser = false
    },

    /* 维修组选择 */
    onGroupChoice (e) {
	  let id = ''
	  this.getGroupList.forEach((item) => {
	    if (item.groupName === e) id = item.groupId
	  })
	  this.ruleForm.groupId = id
      this.ruleForm.groupName = e
	  this.userInfo = []
	  this.repairUserList = []
	  this.getGroupList.forEach(item => {
	    if (item.groupName === e) {
	      this.userInfo = item.groupUsers
	  		  item.groupUsers.forEach((item) => {
	  		    this.userInfoNames.push(item.userName)
	  		  })
	    }
	  })

	  this.showGroup = false
    },

    /* 维修人员选择 */
    onUserChoice (e) {
	  const list = []
	  this.userInfo.forEach((item) => {
	    if (item.userName === e) {
          list.push({ userId: item.userId, userName: item.userName })
        }
	  })
	  this.ruleForm.repairUserName = e
	  this.ruleForm.userList = list
	  this.showUserList = false
    },

    sum (arr) {
      return arr.reduce(function (prev, curr, idx, arr) {
        return prev + curr
      })
    },
    handleSubmit () {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              /** 保存自定义字段 */
              if (this.extension.length > 0) {
                const obj = {}
                this.extension.filter((item, index) => {
                  obj[item.fieldColumn] = item.value ? item.value : ''
                })
                this.ruleForm.extensionInfo = obj
              }
              this.submitApi()
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => {})
    },
    submitApi () {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.$axios
        .post('/dobo-equip/repair/order/insertOrder', this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                if (this.detailsObj.nums === 1) {
                  this.$router.push('/equipmentInspection')
                } else {
                  this.$router.push('/eqMaintain')
                }
              })
              .catch(() => {})
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              if (this.detailsObj.nums === 1) {
                this.$router.push('/equipmentInspection')
              } else {
                this.$router.push('/eqMaintain')
              }
            }, 1000)
          }
        })
        .catch(() => {})
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        if (this.detailsObj.nums === 1) {
          this.$router.push('/equipmentInspection')
        } else {
          this.$router.push('/eqMaintain')
        }
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .formDivBox {
    .van-field {
      border: 1px solid #f5f5f5;
    }
  }
  .pStyle {
    height: 35px;
    line-height: 35px;
    background: #f5f5f5;
    text-align: center;
  }
  .extensionDiv {
    overflow: hidden;
    .van-field {
      width: 50%;
      float: left;
      border: 1px solid #f5f5f5;
    }
  }
}
</style>
<style lang='scss'>
.formDivBox {
  .van-field__label {
    font-size: 17px !important;
  }
  .van-field__control {
    font-size: 17px !important;
  }
}
</style>
